//
//  NewsMoreVC.m
//  sensen_ios
//
//  Created by mc on 16/3/23.
//  Copyright © 2016年 pro. All rights reserved.
//

#import "NewsMoreVC.h"


#import "NewsCell.h"

#import "PostReplyModel.h"
#import "WebVC.h"

@interface NewsMoreVC ()<UITableViewDataSource, UITableViewDelegate>{
    UITableView *_tableView;
    UIImageView *_headerView;
    NSInteger _page_no;//页码,默认0
    NSInteger _pageSize;//每页显示个数，默认10,最大30,最小1,
}

@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) UIView * emptyView;

@end

@implementation NewsMoreVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self _initTableView];
    self.dataArray = [NSMutableArray arrayWithCapacity:1];
    
    [self _getData];
    // 刷新
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(_getData)];
    _tableView.header = header;
    
    // 下拉加载更多
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(_getMoreData)];
    _tableView.footer = footer;
    
    // Do any additional setup after loading the view.
}




- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:YES];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    
    // 设置导航栏颜色
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageWithColor:SS_NAVI_ORANGE_COLOR] forBarMetrics:UIBarMetricsDefault];
    // 隐藏标签栏
    MainTabBarController *main = (MainTabBarController *)self.navigationController.tabBarController;
    [main hideTabBar];
    
}

// 创建表视图
- (void)_initTableView {
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 36 - 64) style:UITableViewStyleGrouped];
    _tableView.backgroundColor = [UIColor whiteColor];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.hidden = YES;
    [self.view addSubview:_tableView];
    
    
    _headerView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_WIDTH / 2)];
    //_headerView.image = [UIImage imageNamed:@"新闻大图"];
    _headerView.userInteractionEnabled = YES;
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapHeaderAction:)];
    [_headerView addGestureRecognizer:tap];
    _tableView.tableHeaderView = _headerView;
    [self _initNoDataView];
}


// 创建没有订单视图
- (void)_initNoDataView{
    _emptyView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 36 - 64)];
    [self.view addSubview:_emptyView];
    UILabel *lable = [[UILabel alloc] init];
    [_emptyView addSubview:lable];
    _emptyView.hidden = YES;
    [lable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(_emptyView.mas_centerX).offset(0);
        make.centerY.equalTo(_emptyView.mas_centerY).offset(-100);
        make.size.mas_equalTo(CGSizeMake(200, 20));
    }];
    
    
    //lable.text = @"网速不给力，点击屏幕重试";
    lable.textColor = [UIColor lightGrayColor];
    lable.font = [UIFont systemFontOfSize:13];
    lable.textAlignment = NSTextAlignmentCenter;
    
    UILabel *lable1 = [[UILabel alloc] init];
    [_emptyView addSubview:lable1];
    
    [lable1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(_emptyView.mas_centerX).offset(0);
        make.top.equalTo(lable.mas_bottom).offset(0);
        make.size.mas_equalTo(CGSizeMake(200, 20));
    }];
    
    lable1.text = @"马上去其他地方逛逛吧";
    lable1.textColor = [UIColor blackColor];
    lable1.font = [UIFont systemFontOfSize:15];
    lable1.textAlignment = NSTextAlignmentCenter;
    
}





- (void)_getData {
    [SVProgressHUD showWithStatus:@"正在加载..."]; // 请求中
    NSMutableDictionary *  diction = [NSMutableDictionary dictionaryWithCapacity:0];
    _page_no = 1;
    _pageSize = 10;
    [diction setObject:[NSString stringWithFormat:@"%ld", (long)_pageSize] forKey:@"pageSize"];
    [diction setObject:[NSString stringWithFormat:@"%ld", (long)_page_no] forKey:@"page_no"];
    if (self.type == 0) {//时政要闻 6049
        [diction setObject:@"6049" forKey:@"position"];
    }else if (self.type == 2){// 休闲娱乐 6050
         [diction setObject:@"6050" forKey:@"position"];
    }else if (self.type == 4){// 周末走呗 6051
         [diction setObject:@"6051" forKey:@"position"];
    }else if (self.type == 3){// 宠物世界 6052
         [diction setObject:@"6052" forKey:@"position"];
    }else if (self.type == 5){// 心灵微光 6053
         [diction setObject:@"6053" forKey:@"position"];
    }else if (self.type == 1){//森森夜话 6082
        [diction setObject:@"6082" forKey:@"position"];
    }
  
    __weak typeof (self) weakSelf = self;
    [BoyeHttpClient post:@"BY_News_query" apiVerson:101 params:diction success:^(AFHTTPRequestOperation *operation, id result) {
        _tableView.hidden = NO;
        [SVProgressHUD dismiss];
          NSLog(@"%@", result);
         if (![result[@"list"] isKindOfClass:[NSNull class]]) { // 有数据
             if (weakSelf.dataArray == nil) {
                 weakSelf.dataArray = [NSMutableArray arrayWithCapacity:1];
             }else{
                 [weakSelf.dataArray removeAllObjects];
             }
             
             
             
             NSArray * array = result[@"list"];
             for (NSDictionary * dic in array) {
                 
                 PostReplyModel * model = [[PostReplyModel alloc] init];
                 model.fid = dic[@"id"];
                 model.main_img = dic[@"main_img"];
                 model.post_excerpt = dic[@"post_excerpt"];
                 model.post_title = dic[@"post_title"];
                 [weakSelf.dataArray addObject:model];
             }
             
            PostReplyModel * model = [weakSelf.dataArray objectAtIndex:0];
            [_headerView setImageURLStr:model.main_img placeholder:DEFAULT_CAROUSEL_IMAGE];
            [_tableView reloadData];
             
         }else{
             _tableView.hidden = YES;
             _emptyView.hidden = NO;
             
         }
        
        if (weakSelf.dataArray.count == [result[@"count"] integerValue]) {
            [_tableView.footer noticeNoMoreData];
        }
        

        [_tableView.header endRefreshing];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [SVProgressHUD dismiss];
        [_tableView.header endRefreshing];
        
        _tableView.hidden = YES;
        _emptyView.hidden = NO;
        
    }];
}



- (void)_getMoreData{
    [SVProgressHUD showWithStatus:@"正在加载..."]; // 请求中
    NSMutableDictionary *  diction = [NSMutableDictionary dictionaryWithCapacity:0];
    _page_no += 1;
    _pageSize = 10;
    [diction setObject:[NSString stringWithFormat:@"%ld", (long)_pageSize] forKey:@"pageSize"];
    [diction setObject:[NSString stringWithFormat:@"%ld", (long)_page_no] forKey:@"page_no"];
    if (self.type == 0) {//时政要闻 6049
        [diction setObject:@"6049" forKey:@"position"];
    }else if (self.type == 2){// 休闲娱乐 6050
        [diction setObject:@"6050" forKey:@"position"];
    }else if (self.type == 4){// 周末走呗 6051
        [diction setObject:@"6051" forKey:@"position"];
    }else if (self.type == 3){// 宠物世界 6052
        [diction setObject:@"6052" forKey:@"position"];
    }else if (self.type == 5){// 心灵微光 6053
        [diction setObject:@"6053" forKey:@"position"];
    }else if (self.type == 1){//森森夜话 6082
        [diction setObject:@"6082" forKey:@"position"];
    }
    
    __weak typeof (self) weakSelf = self;
    [BoyeHttpClient post:@"BY_News_query" apiVerson:101 params:diction success:^(AFHTTPRequestOperation *operation, id result) {
        _tableView.hidden = NO;
        if (![result[@"list"] isKindOfClass:[NSNull class]]) { // 有数据
            
            NSArray * array = result[@"list"];
            for (NSDictionary * dic in array) {
                
                PostReplyModel * model = [[PostReplyModel alloc] init];
                model.fid = dic[@"id"];
                model.main_img = dic[@"main_img"];
                model.post_excerpt = dic[@"post_excerpt"];
                model.post_title = dic[@"post_title"];
                [weakSelf.dataArray addObject:model];
            }
            
            [_tableView reloadData];
        }
        
        
        if (weakSelf.dataArray.count == [result[@"count"] integerValue]) {
            [_tableView.footer noticeNoMoreData];
        }else{
            [_tableView.footer endRefreshing];
        }

        [SVProgressHUD dismiss];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [SVProgressHUD dismiss];
        [_tableView.footer endRefreshing];
    }];

    
    
}

#pragma mark - UITableViewDataSource UITableViewDelegate
// 设置组数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
// 设置行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
     return self.dataArray.count - 1;
    
}



// 设置单元格属性
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    PostReplyModel * model = [self.dataArray objectAtIndex:indexPath.row + 1];
    NewsCell *cell = [NewsCell cellWithTableView:tableView];
    cell.model = model;
    return cell;
    
}


// 设置单元格高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 80;
    
    
}
// 设置组头高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
//    if (section == 1) {
//        return 100;
//    }else{
        return 5;
//    }
    
}


//- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
//    if (section == 1) {
//        UIView * view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 100)];
//        view.backgroundColor = rgba(238, 238, 238, 1);
//        CGFloat width = (SCREEN_WIDTH -25 ) / 3;
//        
//        
//        UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
//        
//        [view addGestureRecognizer:tap];
//        
//        
//        for (int i = 0; i < 3; i++) {
//            UIImageView * imageView = [[UIImageView alloc] init];
//            imageView.image = [UIImage imageNamed:@"新闻中图"];
//            [view addSubview:imageView];
//            if (i == 0) {
//                [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
//                    make.left.equalTo(view).offset(8);
//                    make.centerY.equalTo(view).offset(0);
//                    make.size.mas_equalTo(CGSizeMake(width, view.height - 10));
//                }];
//            }else if (i == 1){
//                [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
//                    
//                    make.centerX.equalTo(view).offset(0);
//                    make.centerY.equalTo(view).offset(0);
//                    make.size.mas_equalTo(CGSizeMake(width, view.height - 10));
//
//                    
//                }];
//            }else if (i == 2){
//                
//                [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
//                    
//                    make.right.equalTo(view).offset(-8);
//                    make.centerY.equalTo(view).offset(0);
//                    make.size.mas_equalTo(CGSizeMake(width, view.height - 10));
//                    
//                }];
//                
//                
//            }
//        }
//        
//        return view;
//    }else{
//        return nil;
//    }
//}


// 设置组尾高度
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
//    if (section == 0) {
//        return 30;
//    }else{
        return 5;
//    }
}

//- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
//    if (section == 0) {
//        UILabel * lable = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 30)];
//        lable.textColor = [UIColor grayColor];
//        lable.text = @"  伦敦水族官迎来年度大扫除 萌鱼围观呆头呆脑";
//        lable.font = [UIFont systemFontOfSize:13];
//        lable.backgroundColor = rgba(238, 238, 238, 1);
//        return lable;
//    }else{
//        return nil;
//    }
//}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];// 取消选中阴影
    PostReplyModel * model = [self.dataArray objectAtIndex:indexPath.row + 1];
    WebVC *vc = [[WebVC alloc] initWithUrlString:[NSString stringWithFormat:@"Post/viewPost?id=%@&from=app",model.fid]];
    vc.titleString = @"新闻详情";
    vc.model = model;
    //[vc createRightBarButtonItemWithImagename:@"论坛首页_详情页_分享"];
    [self.navigationController pushViewController:vc animated:YES];    
}

- (void)tapAction:(UITapGestureRecognizer *)tap{
    NSLog(@"点击了三个图片");
}
- (void)tapHeaderAction:(UITapGestureRecognizer *)tap{
    NSLog(@"点击了大图");
    
    PostReplyModel * model = [self.dataArray firstObject];
    NSLog(@"%@", model.fid);
    WebVC *vc = [[WebVC alloc] initWithUrlString:[NSString stringWithFormat:@"Post/viewPost?id=%@&from=app",model.fid]];
    vc.titleString = @"新闻详情";
    vc.model = model;
    //[vc createRightBarButtonItemWithImagename:@"论坛首页_详情页_分享"];
    [self.navigationController pushViewController:vc animated:YES];

}


#pragma mark 分割线距离左边距离
-(void)viewDidLayoutSubviews
{
    if ([_tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [_tableView setSeparatorInset:UIEdgeInsetsMake(0,0,0,0)];
    }
    if ([_tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [_tableView setLayoutMargins:UIEdgeInsetsMake(0,0,0,0)];
    }
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsMake(0,0,0,0)];
    }
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsMake(0,0,0,0)];
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
